package com.gitee.jmash.rbac.utils;

import com.gitee.jmash.common.cache.SerialCache;
import com.gitee.jmash.rbac.model.UserOpenCreateReq;
import com.xyvcard.wechat.client.WechatClient;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.UUID;
import jmash.rbac.protobuf.MobileAppLoginBindPhoneReq;
import jmash.rbac.protobuf.MobileAppLoginReq;
import jmash.rbac.protobuf.OpensType;
import xyvcard.wechat.protobuf.MobileAppUserOpenIdReq;
import xyvcard.wechat.protobuf.MobileAppUserOpenIdResp;

/**
 * @author wyy
 * 2025/2/14 15:30
 */
public class MobileAppUtil {

  private static String OPENID_PERFIX = "weixin:openid:";

  /** 缓存. */
  public static SerialCache getCache() {
    return CDI.current().select(SerialCache.class).get();
  }

  /**
   * 获取openId
   */
  public static MobileAppUserOpenIdResp getUserOpenId(@NotNull @Valid MobileAppLoginReq req) {
    MobileAppUserOpenIdReq.Builder builder = MobileAppUserOpenIdReq.newBuilder();
    builder.setTenant(req.getTenant()).setAuthorizerAppid(req.getAppId())
        .setLoginCode(req.getLoginCode());
    MobileAppUserOpenIdResp resp =
        WechatClient.getWechatBlockingStub().findMobileAppUserOpenId(builder.build());
    return resp;
  }

  /**
   * 缓存OpenId
   * @param resp
   * @return
   */
  public static String cacheOpenId(MobileAppUserOpenIdResp resp) {
    String cacheKey = UUID.randomUUID().toString();
    // 缓存10分钟.
    getCache().put(OPENID_PERFIX + cacheKey, resp, 10 * 60);
    return cacheKey;
  }

  public static MobileAppUserOpenIdResp getCacheOpenId(String cacheKey) {
    return (MobileAppUserOpenIdResp) getCache().get(OPENID_PERFIX + cacheKey);
  }

  // 获取用户注册绑定登录信息.
  public static UserOpenCreateReq getCreateUserInfo(
      @NotNull @Valid MobileAppLoginBindPhoneReq req, MobileAppUserOpenIdResp openIdResp) {
    UserOpenCreateReq user = new UserOpenCreateReq();
    user.setOpenType(OpensType.wechat);
    user.setAppid(req.getAppId());
    user.setNickName(req.getNickName());
    user.setTenant(req.getTenant());
    user.setOpenid(openIdResp.getOpenId());
    user.setUnionid(openIdResp.getUnionId());
    user.setMobilePhone(req.getPhoneNumber());
    return user;
  }

}
